import std.stream;
import std.file;
import std.regexp;

import ImageIO;
import ImageI;

public class Images{
	ImageIO[] images;
	int width;
	int height;
	uint bg;
	uint fg;
	int current = -1;

	this(int width, int height, uint bg, uint fg){
		this.width = width;
		this.height = height;
		this.bg = bg;
		this.fg = fg;
		char[][] f = listdir(`./pic/`,RegExp(`\.mm$`, null));
		images.length = f.length;
		foreach(int i, char[] ln; f)
			addFromFile(ln, i);
	}

	void addFromFile(char[] path, int nr){
		ImageIO img = new ImageIO(width, height, bg, fg);
		File f = new File(path);
		int ln = 0;
		
		while (!f.eof()){
			char[] line = f.readLine();
			assert(line.length == width);
			for(int i = 0; i < width; i++)
				if(line[i] == '0')
					img.pixels[ln][i] = bg;
				else if(line[i] == '1')
					img.pixels[ln][i] = fg;
			ln++;
		}
		assert(ln == height);
		images[nr] = img;
		f.close();
	}

	void addFromBox(ImageI img){
		File f = new File("./pic/"~std.string.toString(images.length)~".mm", FileMode.Out);
		foreach(line; img.pixels){
			char[] buf;
			foreach(znak; line)
				if(znak == fg)
					buf ~= '1';
				else if(znak == bg)
					buf ~= '0';
			f.writeLine(buf);
		}
		f.close();

		ImageIO image = new ImageIO(width, height, bg, fg);
		foreach(int i,line; img.pixels)
			image.pixels[i][0..$] = line[0..$];
		images.length = images.length + 1;
		images[images.length - 1] = image;
	}

	void getNext(inout ImageI img){
		current++;
		if(current >= images.length)
			current = 0;
		assert(current < images.length);
		foreach(int i,inout line; img.pixels){
			line[0..$] = images[current].pixels[i][0..$];
		}
	}

    void getPrevious(inout ImageI img){
        current--;
        if(current < 0)
            current = images.length - 1;
        assert(current < images.length);
        foreach(int i,inout line; img.pixels){
            line[0..$] = images[current].pixels[i][0..$];
        }
    }


}
